from django.contrib.auth.backends import ModelBackend
import re
from .models import User




class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        重写认证方法，实现多账号登录
        :param request: 请求对象
        :param username: 用户名
        :param password: 密码
        :param kwargs: 其他参数
        :return: user
        """
        # 根据传入的username获取user对象。username可以是手机号也可以是账号
        # 若果用户名满足手机号,否则就是用户名
        try:

            if re.match(r'1[3-9]\d{9}', username):
                user = User.objects.get(mobile=username)
            else:
                # 否则就是 用户名登陆

                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None


            # 再判断密码是否正确
        if user.check_password(password) and self.user_can_authenticate(user):
            return user




from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

def generate_verify_email_url(user):
    """
    生成邮箱验证链接
    :param user: 当前登录用户
    :return: verify_url
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    data = {'id': user.id}
    token = serializer.dumps(data).decode()

    verify_url = 'http://www.meiduo.site:8000/email_active/?token=' + token

    return verify_url


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings


def check_verify_email_token(token):
    """
    验证token并提取user
    :param token: 用户信息签名后的结果
    :return: user, None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    try:
        result= serializer.loads(token)
    except Exception:
        return None
    return result.get('id')